// Labels Admin page scripts
(function () {
  'use strict';

  // Utility Functions
  // ================

  /**
   * Run a function when the DOM is fully loaded and Bootstrap is available
   * @param {Function} fn - The function to run when ready
   */
  function ready(fn) {
    if (document.readyState === 'complete' || document.readyState === 'interactive') {
      if (window.bootstrap) {
        fn();
      } else {
        window.addEventListener('load', fn);
      }
    } else {
      document.addEventListener('DOMContentLoaded', function() {
        if (window.bootstrap) {
          fn();
        } else {
          window.addEventListener('load', fn);
        }
      });
    }
  }

  /**
   * Get a cookie value by name
   * @param {string} name - The name of the cookie to retrieve
   * @returns {string|null} The cookie value or null if not found
   */
  function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(';').shift();
    return null;
  }

  /**
   * Show a Bootstrap alert message
   * @param {string} type - Alert type (success, danger, warning, info)
   * @param {string} message - The message to display
   */
  function showAlert(type, message) {
    const div = document.createElement('div');
    div.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    div.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    div.innerHTML = `
      ${message}
      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;
    document.body.appendChild(div);
    setTimeout(() => div.remove(), 5000);
  }

  // State Management
  // ===============
  let currentTemplateId = null;

  // Template Actions
  // ===============

  function previewTemplate(templateId) {
    console.log('Preview template:', templateId);
    currentTemplateId = templateId;
    // Implementation here
  }

  function editTemplate(templateId) {
    console.log('Edit template:', templateId);
    currentTemplateId = templateId;
    
    // Show loading state
    const modal = document.getElementById('editTemplateModal');
    if (!modal) {
      console.error('Edit template modal not found');
      return;
    }
    
    // Initialize modal if not already done
    if (window.bootstrap) {
      const bsModal = new bootstrap.Modal(modal);
      bsModal.show();
    } else {
      modal.style.display = 'block';
    }
  }

  function useTemplate(templateId) {
    console.log('Use template:', templateId);
    // Implementation here
  }

  function duplicateTemplate(templateId) {
    console.log('Duplicate template:', templateId);
    // Implementation here
  }

  function deleteTemplate(templateId) {
    console.log('Delete template:', templateId);
    if (confirm('确定要删除此模板吗？此操作无法撤销。')) {
      // Implementation here
    }
  }

  function createQuickTemplate(type) {
    console.log('Create quick template:', type);
    // Implementation here
  }

  function importTemplates() {
    console.log('Import templates');
    // Implementation here
  }

  function exportTemplates() {
    console.log('Export templates');
    // Implementation here
  }

  function confirmImport() {
    console.log('Confirm import');
    // Implementation here
  }

  function confirmExport() {
    console.log('Confirm export');
    // Implementation here
  }

  function printPreview() {
    if (currentTemplateId) {
      useTemplate(currentTemplateId);
    }
  }

  // Form Handlers
  // ============

  /**
   * Handle save template form submission
   * @param {Event} e - The form submission event
   */
  function handleSaveTemplate(e) {
    e.preventDefault();
    
    const form = document.getElementById('edit-template-form');
    if (!form) {
      console.error('Edit template form not found');
      return;
    }

    const formData = new FormData(form);
    const templateId = document.getElementById('edit-template-id')?.value;
    const submitBtn = document.getElementById('save-template-btn');

    if (!templateId || !submitBtn) {
      console.error('Required elements not found');
      return;
    }

    const originalBtnText = submitBtn.innerHTML;

    // Show loading state
    submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 保存中...';
    submitBtn.disabled = true;

    // Prepare data object from form data
    const data = {};
    formData.forEach((value, key) => {
      data[key] = value;
    });

    // Send update request
    fetch(`/api/label-templates/${templateId}/`, {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': getCookie('csrftoken')
      },
      body: JSON.stringify(data)
    })
    .then(response => {
      if (!response.ok) {
        return response.json().then(err => {
          throw new Error(err.message || 'Failed to update template');
        });
      }
      return response.json();
    })
    .then(data => {
      showAlert('success', '模板更新成功');
      // Close the modal
      const modal = bootstrap.Modal.getInstance(document.getElementById('editTemplateModal'));
      if (modal) modal.hide();
      // Reload the page to show changes
      window.location.reload();
    })
    .catch(error => {
      console.error('Error:', error);
      showAlert('danger', '保存失败: ' + error.message);
    })
    .finally(() => {
      if (submitBtn) {
        submitBtn.innerHTML = originalBtnText;
        submitBtn.disabled = false;
      }
    });
  }

  // Event Handlers
  // =============

  /**
   * Initialize all event handlers
   */
  function initializeEventHandlers() {
    console.log('Initializing event handlers...');
    console.log('jQuery available:', !!window.jQuery);
    console.log('Bootstrap available:', !!window.bootstrap);

    // Save button event listener
    const saveBtn = document.getElementById('save-template-btn');
    if (saveBtn) {
      saveBtn.removeEventListener('click', handleSaveTemplate);
      saveBtn.addEventListener('click', handleSaveTemplate);
    }

    // Initialize modals
    const editModal = document.getElementById('editTemplateModal');
    if (editModal && window.bootstrap) {
      if (!bootstrap.Modal.getInstance(editModal)) {
        new bootstrap.Modal(editModal);
      }
    }

    // Global click handler for template actions
    document.addEventListener('click', (e) => {
      // Handle template action buttons
      const actionBtn = e.target.closest('[data-action]');
      if (actionBtn) {
        const action = actionBtn.dataset.action;
        const templateId = actionBtn.dataset.templateId;
        
        switch (action) {
          case 'edit':
            editTemplate(templateId);
            break;
          case 'preview':
            previewTemplate(templateId);
            break;
          case 'use':
            useTemplate(templateId);
            break;
          case 'duplicate':
            duplicateTemplate(templateId);
            break;
          case 'delete':
            deleteTemplate(templateId);
            break;
        }
      }

      // Handle quick actions
      const quickBtn = e.target.closest('.quick-action-btn');
      if (quickBtn) {
        const quickType = quickBtn.dataset.quickType;
        const action = quickBtn.dataset.action;
        
        if (quickType) {
          createQuickTemplate(quickType);
        } else if (action === 'import') {
          importTemplates();
        } else if (action === 'export') {
          exportTemplates();
        }
      }
    });
  }

  // Global Exports
  // =============
  window.previewTemplate = previewTemplate;
  window.editTemplate = editTemplate;
  window.useTemplate = useTemplate;
  window.duplicateTemplate = duplicateTemplate;
  window.deleteTemplate = deleteTemplate;
  window.createQuickTemplate = createQuickTemplate;
  window.importTemplates = importTemplates;
  window.exportTemplates = exportTemplates;
  window.confirmImport = confirmImport;
  window.confirmExport = confirmExport;
  window.printPreview = printPreview;
  window.handleSaveTemplate = handleSaveTemplate;
  window.initializeEventHandlers = initializeEventHandlers;

  // Initialization
  // =============
  
  // Check if Bootstrap is loaded and initialize
  function checkBootstrapAndInitialize() {
    if (window.bootstrap) {
      initializeEventHandlers();
    } else {
      setTimeout(checkBootstrapAndInitialize, 100);
    }
  }

  // Start initialization when document is ready
  ready(() => {
    console.log('Document ready, initializing...');
    checkBootstrapAndInitialize();
  });

})();
